//用户vuex数据模块
import { checkLoginReq, userInfo } from "@/api/user"

const state = {
    token: localStorage.getItem('t_k'),
    role: localStorage.getItem('role'),
    userInfo: {}
}

const getters = {}
const mutations = {
    SET_TOKEN(state, data) {
        //存进vuex
        state.token = data
        //token存本地
        localStorage.setItem('t_k', data)
    },
    SET_ROLE(state, data) {
        state.role = data
        localStorage.setItem('role', data)
    },
    SET_USERINFO(state, data) {
        state.userInfo = data
    },
    CLEAR(state) {
        state.userInfo = {},
        state.token = '',
        state.role = ''
        //清空本地
        localStorage.clear()
    }
}
//异步
const actions = {
    //登录
    A_login({ commit }, data) {
        //凡是actions里面有异步 必须用promise包一层
        return new Promise(async resolve => {
            //发送请求
            let res = await checkLoginReq(data)
            //解析数据
            console.log(res);
            let { code, token, role } = res.data
            //判断
            if (code === 0) {
                commit('SET_TOKEN', 'Bearer ' + token)
                commit('SET_ROLE', role)

                //切换promise 状态为已成功
                resolve()
            }
        })
    },
    //个人中心
    A_userInfo({ commit }) {
        return new Promise(async (resolve, reject) => {
            // let res = await userInfo()
            // console.log(res);
            // commit('SET_USERINFO', res.data)

            // resolve()
            userInfo()
                .then(res => {
                    commit('SET_USERINFO', res.data)
                    resolve(res)
                })
                .catch(err => {
                    reject(err)
                })
        })
    },

    A_clear({ commit }) {
        return new Promise(resolve => {
            commit('CLEAR')
            resolve()
        })
    }

}

export default {
    namespaced: true,
    state,
    getters,
    mutations,
    actions,
}